package com.sitech.openapi.service;

import com.sitech.openapi.componet.BusiConst;
import com.sitech.openapi.componet.MapBean;
import com.sitech.openapi.componet.WSClientService;
import com.sitech.openapi.dto.OrderAttrHis;
import com.sitech.openapi.mapper.BroadBandProdInstMapper;
import com.sitech.openapi.mapper.CommonMapper;
import com.sitech.openapi.mapper.OrderAttrHisMapper;
import com.sitech.openapi.mapper.ProdPreOrderMapperService;
import com.sitech.openapi.utils.DateUtil;
import com.sitech.openapi.utils.NumberUtil;
import com.sitech.openapi.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhangsq on 2018/12/20.
 */
@Service
@Slf4j
public class BroadBandProdInstServiceImpl implements BroadBandProdInstService {

    @Autowired
    BroadBandProdInstMapper broadBandProdInstMapper;
    @Autowired
    ProdPreOrderMapperService prodPreOrderMapperServcie;
    @Autowired
    CommonMapper commonMapper;
    @Autowired
    WSClientService wsClientService;
    @Autowired
    OrderAttrHisMapper orderAttrHisMapper;

    public Map doQryBroadBandProdInst(Map inMap) throws Exception {
        Map prodInstMap = new HashMap();
        try {
            log.info("BroadBandProdInstServiceImpl.doQryBroadBandProdInst==============开始" );
            prodInstMap = broadBandProdInstMapper.getProdInstInfo(inMap);
            inMap.clear();
            if (prodInstMap != null) {
                inMap.put("prodInstId", prodInstMap.get("prodInstId"));
                List attrList = broadBandProdInstMapper.getAttrInfo(prodInstMap);
                prodInstMap.put("attrInfos", attrList);
            }
            log.info("BroadBandProdInstServiceImpl.doQryBroadBandProdInst==============完成" );
        } catch (Exception e) {
            log.info(e.getMessage());
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return prodInstMap;
    }

    public Map doAddBroadBandProdInst(Map inMap) throws Exception {
        try {
            log.info("BroadBandProdInstServiceImpl.doAddBroadBandProdInst==============开始" );
            String extCustOrderId = StringUtil.obj2Str(inMap.get("extCustOrderId"));
            String custOrderId = StringUtil.obj2Str(inMap.get("custOrderId"));
            String channelNbr = StringUtil.obj2Str(inMap.get("channelNbr"));
            String staffCode = StringUtil.obj2Str(inMap.get("staffCode"));
            Map inSqlMap = new HashMap();
            inSqlMap.put("systemUserCode", staffCode);
            Map systemUserInfo = broadBandProdInstMapper.getSystemUserInfo(inSqlMap);
            if (systemUserInfo == null) {
                throw new Exception("没有查到工号" + staffCode + "信息！");
            }
            String commonRegionId = StringUtil.obj2Str(inMap.get("commonRegionId"));
            String lanId = "";
            if (!StringUtils.isEmpty(commonRegionId)) {
                lanId = commonRegionId.substring(1, 5);
            }
            inSqlMap.put("lanId", lanId);
            inSqlMap.put("channelNbr", channelNbr);
            Map channelInfo = broadBandProdInstMapper.getChannelInfo(inSqlMap);
            if (channelInfo == null) {
                throw new Exception("没有查到受理渠道" + channelNbr + "信息！");
            }
            String channelId = (String) channelInfo.get("CHANNEL_ID");
            //产品信息
            Map prodInfo = (Map) inMap.get("prodInfo");
            String accNbr = StringUtil.obj2Str(prodInfo.get("account"));
            String addressDesc = StringUtil.obj2Str(prodInfo.get("addressDesc"));
            Date currentDate = prodPreOrderMapperServcie.queryCurrentDate();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateString = formatter.format(currentDate);

            //调用销售品变更接口 BC930100	SC930101
            Long sequence = commonMapper.getSeq("SEQ_OUTSYSTEMACCEPT");
            String transactionId = BusiConst.PLATFORM_CRM + DateUtil.toStringYmd(DateUtil.getSysDate()) + sequence;
            log.info("业务流水—————————————————————————————" + transactionId);
            //String transactionId = productOrder.getExtCustOrderId();


            MapBean inxmlBean = new MapBean();
            String tcpCont = "ContractRoot.TcpCont.";
            MapBean tcpContBean = new MapBean();
            tcpContBean.setValue(tcpCont + "TransactionID", transactionId);
            tcpContBean.setValue(tcpCont + "ActionCode", "0");
            tcpContBean.setValue(tcpCont + "BusCode", "BC930100");
            tcpContBean.setValue(tcpCont + "ServiceCode", "SC930101");
            tcpContBean.setValue(tcpCont + "ServiceContractVer", "");
            tcpContBean.setValue(tcpCont + "ServiceLevel", "");
            tcpContBean.setValue(tcpCont + "SrcOrgID", "100000");
            tcpContBean.setValue(tcpCont + "SrcSysID", BusiConst.PLATFORM_4GWLW);
            tcpContBean.setValue(tcpCont + "SrcSysSign", "");
            tcpContBean.setValue(tcpCont + "DstOrgID", "609907");
            tcpContBean.setValue(tcpCont + "DstSysID", BusiConst.PLATFORM_CRM);
            tcpContBean.setValue(tcpCont + "ReqTime", DateUtil.toStringYmdHms(DateUtil.getSysDate()));
            tcpContBean.setValue(tcpCont + "Request.ReqType", "");
            tcpContBean.setValue(tcpCont + "Request.ReqCode", "");
            tcpContBean.setValue(tcpCont + "Request.ReqDesc", "");
            tcpContBean.setValue(tcpCont + "ReqSource", "OpenApi");// todo 这个写谁
            tcpContBean.setValue(tcpCont + "Remarks", "");

            MapBean svcBean = new MapBean();
            svcBean.setValue("SvcCont.ChgProdoffer.SYSTEM_USER_CODE", staffCode);
            svcBean.setValue("SvcCont.ChgProdoffer.CHANNEL_ID", channelId);
            svcBean.setValue("SvcCont.ChgProdoffer.ACC_NBR_TYPE_CD", "2");
            svcBean.setValue("SvcCont.ChgProdoffer.ACC_NBR", accNbr);
            svcBean.setValue("SvcCont.ChgProdoffer.OP_CODE", "q031");
            svcBean.setValue("SvcCont.ChgProdoffer.OP_NOTE", "工号" + staffCode + "对号码为" + accNbr + "受理销售品变更业务, 电子渠道宽带续约");
            svcBean.setValue("SvcCont.ChgProdoffer.CHANNEL_SORT", "1000");

            List prodOfferInfoList = (List) inMap.get("prodOfferInfos");
            int m = 0;
            if (prodOfferInfoList != null && prodOfferInfoList.size() > 0) {
                for (int i = 0; i < prodOfferInfoList.size(); i++) {
                    Map prodOfferInfo = (Map) prodOfferInfoList.get(0);
                    String prodOfferNbr = (String) prodOfferInfo.get("prodOfferNbr");
                    inSqlMap.put("offerNbr", prodOfferNbr);
                    List prodOfferList = broadBandProdInstMapper.getProdOfferInfo(inSqlMap);
                    if (prodOfferList == null || prodOfferList.size() == 0) {
                        throw new Exception("查不到要订购的销售品信息！");
                    }
                    Map prodOfferMap = (Map) prodOfferList.get(0);
                    String prodOfferId = StringUtil.obj2Str(prodOfferMap.get("PROD_OFFER_ID"));
                    String serviceOfferId = StringUtil.obj2Str(prodOfferInfo.get("serviceOfferId"));
                    svcBean.setValue("SvcCont.ChgProdoffer.ProdofferList.PROD_OFFER[" + m + "].PROD_OFFER_ID", prodOfferId);
                    svcBean.setValue("SvcCont.ChgProdoffer.ProdofferList.PROD_OFFER[" + m + "].OP_TYPE", "1");
                    svcBean.setValue("SvcCont.ChgProdoffer.ProdofferList.PROD_OFFER[" + m + "].EFF_DATE", dateString);
                    svcBean.setValue("SvcCont.ChgProdoffer.ProdofferList.PROD_OFFER[" + m + "].EXP_DATE", "");
                    m++;
                    int n = 0;
                    List attrInfos = (List) prodOfferInfo.get("attrInfos");
                    if (attrInfos != null && attrInfos.size() > 0) {
                        for (int j = 0; j < attrInfos.size(); j++) {
                            Map attrInfo = (Map) attrInfos.get(j);
                            String attrSpecId = (String) attrInfo.get("attrSpecId");
                            String attrValue = (String) attrInfo.get("attrValue");
                            inSqlMap.put("extAttrCd", attrSpecId);
                            Map attrSpecInfo = broadBandProdInstMapper.getAttrSpecInfo(inSqlMap);
                            if (attrSpecInfo != null) {
                                String attrId = StringUtil.obj2Str(attrSpecInfo.get("ATTR_ID"));
                                svcBean.setValue("SvcCont.ChgProdoffer.ProdofferList.PROD_OFFER[" + m + "].ATTRLIST.ATTR[" + n + "].ATTR_ID", attrId);
                                svcBean.setValue("SvcCont.ChgProdoffer.ProdofferList.PROD_OFFER[" + m + "].ATTRLIST.ATTR[" + n + "].ATTR_VALUE", attrValue);
                                n++;
                            }
                        }
                    }
                    inxmlBean.append(tcpContBean).setMapBeanByPath("ContractRoot", svcBean);
                    String inxml = inxmlBean.toXML();
                    log.info("调用销售品变更接口 入参报文inxml—————————————————————————————" + inxml);
                    String outXml = wsClientService.doQryClientSerive(inxml, BusiConst.URL_CREATE_ORDER);
                    log.info("===========调用销售品变更接口 返回报文=========");
                    log.info(outXml);
                    MapBean mapOfferRstBean = new MapBean();
                    mapOfferRstBean.fromXML(outXml);
                    String resCode = StringUtil.obj2Str(mapOfferRstBean.getValue("ContractRoot.TcpCont.Response.RspCode"));
                    String recDesc = StringUtil.obj2Str(mapOfferRstBean.getValue("ContractRoot.TcpCont.Response.RspDesc"));
                    if (StringUtil.isEqual(resCode, "0000")) {
                        String busiAccept = StringUtil.obj2Str(mapOfferRstBean.getValue("ContractRoot.SvcCont.PEB_BUSI_ORDER.BUSI_ACCEPT"));
                        String crmCustOrderId = StringUtil.obj2Str(mapOfferRstBean.getValue("ContractRoot.SvcCont.PEB_BUSI_ORDER.CUST_ORDER_ID"));
                        inMap.put("custOrderId", crmCustOrderId);
                        String suffix = "20" + crmCustOrderId.substring(0, 4);
                        List suffiexList = new ArrayList<String>();
                        OrderAttrHis orderAttrHis = new OrderAttrHis();
                        suffiexList.add(suffix);
                        orderAttrHis.setTableSuffixs(suffiexList);
                        Long orderAttrId = commonMapper.getSeq("SEQ_ORDER_ATTR_ID");
                        orderAttrHis.setOrderAttrId(orderAttrId);
                        orderAttrHis.setAttrId(184001);
                        orderAttrHis.setCustOrderId(NumberUtil.getLongFromObj(crmCustOrderId));
                        orderAttrHis.setBusiAccept(NumberUtil.getLongFromObj(busiAccept));
                        orderAttrHis.setAttrValue(extCustOrderId);
                        orderAttrHis.setHisAccept(new BigDecimal(busiAccept));
                        orderAttrHis.setHisType("I");
                        orderAttrHis.setHisLogin(staffCode);
                        orderAttrHis.setHisDate(NumberUtil.getLongFromObj(dateString));
                        orderAttrHis.setHisTime(currentDate);
                        orderAttrHis.setAttrName("电子渠道宽带续约省内客户订单与集团外部订单关系");
                        orderAttrHisMapper.insert(orderAttrHis);
                        log.info("调用销售品变更接口 落order_attr_his表成功—————————————————————————————" + crmCustOrderId);
                    } else {
                        throw new Exception(recDesc);
                    }
                }
            }
            log.info("BroadBandProdInstServiceImpl.doAddBroadBandProdInst==============完成" );
        } catch (Exception e) {
            log.info(e.getMessage());
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return inMap;
    }
}
